<template>
  <div class="box">
    <div class="header">
      <van-nav-bar title="购物车" @click-left="onClickLeft">
        <template #left>
          <!-- 返回 -->
          <van-icon name="arrow-left" size="30" color="black" />
        </template>
        <template #right>
          <van-popover
            v-model="showPopover"
            trigger="click"
            :actions="actions"
            @select="onSelect"
            placement="bottom-end"
            theme="dark"
            ref="del"
          >
            <template #reference>
              <!-- ... -->
              <van-icon name="ellipsis" size="30" color="black" />
            </template>
          </van-popover>
        </template>
      </van-nav-bar>
    </div>
    <div class="main">
      <div class="nothing" v-if="empty">
        <van-empty
          class="custom-image"
          image="https://img01.yzcdn.cn/vant/custom-empty-image.png"
          description="购物车数据为空"
        />
      </div>
      <div class="hasthing" v-else :ref="isChecked ? checked : '' ">
        <van-swipe-cell
          v-for="(item, index) in cartList"
          :key="index"
          :name="item.cartid"
          :before-close="beforeClose"
        >
          <van-checkbox
            v-model="item.flag"
            @click="selectOne(item.cartid, item.flag)"
          ></van-checkbox>
          <van-card
            tag="标签"
            :price="item.originprice"
            :title="item.proname"
            :thumb="item.img1"
          >
            <!-- 设置加减  步进器替换 -->
            <template #num>
              <van-stepper
                v-model="item.num"
                theme="round"
                button-size="22"
                disable-input
                @change="addNum(item.cartid, item.num)"
              />
            </template>
          </van-card>
          <template #right>
            <van-button
              square
              text="删除"
              type="danger"
              class="delete-button"
            />
          </template>
        </van-swipe-cell>
        <van-submit-bar
          :price="getMoney"
          button-text="提交订单"
          @submit="onSubmit"
        >
          <van-checkbox v-model="isAll" ref="All"></van-checkbox>
        </van-submit-bar>
        <van-divider>猜你喜欢</van-divider>
        <ul class="recommendList">
          <li
            v-for="(item, index) in recommendList"
            :key="index"
            @click="jumpTo(item.proid)"
          >
            <img :src="item.img1" alt="" width="100%" />
            <div>
              <h4 class="van-multi-ellipsis--l2">{{ item.proname }}</h4>
              <p>￥{{ item.originprice }}</p>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <!-- 分享面板 -->
    <van-share-sheet
      v-model="showShare"
      title="立即分享给好友"
      :options="options"
    />
  </div>
</template>

<script>
import {
  doCartList,
  doUpdateNum,
  doDeleteOne,
  doCheckOne,
  doCheckAll,
  doDeleteAll,
  doRecommendlist,
  addOrder,
} from "../api/cart";
import Vue from "vue";
import {
  Empty,
  Card,
  Stepper,
  SwipeCell,
  Checkbox,
  CheckboxGroup,
  SubmitBar,
  Dialog,
  Divider,
} from "vant";
Vue.use(Empty);
Vue.use(Card);
Vue.use(Stepper);
Vue.use(SwipeCell);
Vue.use(Checkbox);
Vue.use(CheckboxGroup);
Vue.use(SubmitBar);
Vue.use(Dialog);
Vue.use(Divider);
export default {
  name: "Cart",
  components: {},
  data() {
    return {
      empty: true,
      cartList: [],
      recommendList: [],
      isChecked: "",
      showPopover: false,
      actions: [
        { text: "首页", icon: "wap-home-o" },
        { text: "分享", icon: "share-o" },
        { text: "清购物车", icon: "delete-o" },
      ],
      showShare: false,
      options: [
        [
          { name: "微信", icon: "wechat" },
          { name: "朋友圈", icon: "wechat-moments" },
          { name: "微博", icon: "weibo" },
          { name: "QQ", icon: "qq" },
        ],
        [
          { name: "复制链接", icon: "link" },
          { name: "分享海报", icon: "poster" },
          { name: "二维码", icon: "qrcode" },
          { name: "小程序码", icon: "weapp-qrcode" },
        ],
      ],
    };
  },

  created() {
    //判断用户是否登录
    if (localStorage.getItem("token")) {
      this.getCartList();
    } else {
      this.$router.push("/login");
    }
    doRecommendlist({ count: this.count, limitNum: 12 }).then((data) => {
      console.log(data.data.data);
      this.recommendList = data.data.data;
    });
  },
  methods: {
    onClickLeft() {
      this.$router.push("/home");
    },
    jumpTo(proid) {
      this.$router.push("/detail/" + proid);
      //this.$router.push({path:"/detail",params:{proid}})
    },
    onSelect(action, index) {
      switch (index) {
        case 0:
          this.$router.back();
          break;
        case 1:
          this.showShare = true; /*  */
          break;
        case 2:
          //清空购物车
          doDeleteAll({ userid: localStorage.getItem("userid") }).then(
            (res) => {
              console.log(res);
              this.getCartList();
            }
          );
          break;
        default:
          break;
      }
    },
    addNum(cartid, num) {
      //调用加的接口
      doUpdateNum({ cartid, num }).then((res) => {
        console.log(res);
      });
    },
    getCartList() {
      //发送获取购物车请求
      doCartList({ userid: localStorage.getItem("userid") }).then((res) => {
        console.log(res.data.code);
        if (res.data.code == "10020") {
          //没有数据
          this.empty = true;
        } else {
          //有数据
          this.empty = false;
          this.cartList = res.data.data;
        }
      });
    },
    beforeClose({ name, position, instance }) {
      console.log(name, position, instance);
      switch (position) {
        case "right":
          Dialog.confirm({
            message: "确定删除吗？",
          })
            .then(() => {
              //点击确定删除执行这里
              doDeleteOne({ cartid: name }).then((res) => {
                console.log(res);
                if (res.data.code == "200") {
                  this.getCartList();
                }
              });
              instance.close();
            })
            .catch(() => {
              instance.close();
            });
          break;

        default:
          break;
      }
    },
    //单选
    selectOne(cartid, flag) {
      doCheckOne({ cartid, flag }).then((res) => {
        console.log(res);
      });
    },
    //点击提交需购买商品清空
    onSubmit() {
        addOrder({ userid: localStorage.getItem("userid") }).then((res) => {
          console.log(res.data.time);
          if (res.data.code == 200) {
            this.$router.push("/order/" + res.data.time);
          }
        });
      }
  },
  computed: {
    isAll: {
      set(val) {
        this.cartList.forEach((item) => (item.flag = val));
        doCheckAll({ userid: localStorage.getItem("userid"), type: val }).then(
          (res) => {
            console.log(res);
          }
        );
      },
      get() {
        return this.cartList.every((item) => item.flag == true);
      },
    },
    getMoney() {
      let sum = this.cartList.reduce((sum, item) => {
        if (item.flag) {
          sum += item.originprice * item.num;
        }
        return sum;
      }, 0);
      return sum * 100;
    },
  },
};
</script>

<style scoped>
.delete-button {
  height: 100%;
}
::v-deep .van-swipe-cell__wrapper {
  background-color: #fff;
  display: flex;
}
::v-deep .van-checkbox {
  width: 0.3rem;
}
::v-deep .van-card {
  background-color: #fff;
  flex: 1;
}
.van-submit-bar {
  bottom: 0.45rem;
}
.recommendList {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.recommendList li {
  width: 49%;
}
.recommendList li div p {
  color: red;
  font-size: 0.2rem;
  font-weight: bold;
  margin-bottom: 0.2rem;
}
</style>